package com.liholin.springboot.sample.utils;

import okhttp3.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class OkHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    public static String getQueryString(String url, Map<String, String> queries) {
        StringBuilder sb = new StringBuilder(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            for (Map.Entry<String, String> entry : queries.entrySet()) {
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 调用okhttp的newCall方法
     *
     * @param request
     * @return
     */
    private static String execNewCall(Request request) {
        Response response = null;
        try {
            OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * 添加头部参数
     * @param headers 头部参数
     * @return Request.Builder
     */
    private static Request.Builder addHeardToRequest(Map<String, String> headers) {
        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.keySet().size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return builder;
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，后面的数据，没有可以传null
     * @param headers 请求头部 没有可以传null
     * @return 返回结果
     */
    public static String get(String url, Map<String, String> queries, Map<String, String> headers) {
        String urlNew = getQueryString(url, queries);
        Request request = addHeardToRequest(headers).url(urlNew).build();
        return execNewCall(request);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param queries 请求的参数，后面的数据，没有可以传null
     * @param params post form 提交的参数
     * @param headers 请求头部 没有可以传null
     * @return 返回结果
     */
    public static String postFormParams(String url, Map<String, String> queries, Map<String, String> params, Map<String, String> headers) {
        String urlNew = getQueryString(url, queries);
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = addHeardToRequest(headers).url(urlNew).post(builder.build()).build();
        return execNewCall(request);
    }


    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * @param url：请求Url
     * @param queries 请求的参数，后面的数据，没有可以传null
     * @param jsonParams：请求的JSON
     * @param headers 请求头部 没有可以传null
     * @return 返回结果
     */
    public static String postJsonParams(String url, Map<String, String> queries, String jsonParams, Map<String, String> headers) {
        String urlNew = getQueryString(url, queries);
        RequestBody requestBody = RequestBody.Companion.create(jsonParams, MediaType.Companion.parse("application/json; charset=utf-8"));
        Request request = addHeardToRequest(headers).url(urlNew).post(requestBody).build();
        return execNewCall(request);
    }

    /**
     * Post请求发送xml数据....
     * @param url：请求Url
     * @param xml：xmlString
     * @param headers 请求头部 没有可以传null
     * @return 返回结果
     */
    public static String postXmlParams(String url, String xml, Map<String, String> headers) {
        RequestBody requestBody = RequestBody.Companion.create(xml, MediaType.Companion.parse("application/xml; charset=utf-8"));
        Request request = addHeardToRequest(headers).url(url).post(requestBody).build();
        return execNewCall(request);
    }
}
